<template>
  <!-- 企业实名认证(法定代表人身份认证) -->
  <view class="ag_container">
    <!-- 页头 -->
    <view class="agree_jn">
      <!-- 步骤条 -->
      <uni-steps :options="steps" :active="0" active-color="#00a660"></uni-steps>
      <p class="care_p">
        为保证您单位通过励氪签平台签署的文件，符合国家法律、法规，贵单位须完成实名认证，验证真实身份。贵单位信息仅用于实名认证，平台已采用安全加密技术存储您的信息，请放心使用！
      </p>
      <!-- 表单填写 -->
      <uni-forms ref="ruleForm" :modelValue="ruleForm" :rules="rules" label-position="top" label-width="400rpx">
        <!-- 组织类型 -->
        <uni-forms-item label="单位组织类型" name="companyTypeId" :required="true">
          <uni-data-select
              v-model="ruleForm.companyTypeId"
              :localdata="companyTypeArr"
              :clear="false"
              @change="selectCompanyTypeId"
          ></uni-data-select>
        </uni-forms-item>
        <!-- 上传证件 -->
        <uni-forms-item label="多合一营业执照" name="file" :required="true">
          <view style="display: flex;align-items: center;margin-bottom:30rpx;">
            <img :src="businessImg" style="width: 200rpx;height: 135rpx;" @click="previewImg(businessImg)">
            <view class="img_span">
              <view style="margin-bottom: 25rpx;">请按示例图要求，上传加盖公章的营业执照复印件。支持 .jpg .jpeg .png 格式，文件小于3M。</view>
              <uni-tag text="上传执照" type="primary" @click="handleFileChange"/>
            </view>
          </view>
        </uni-forms-item>
        <!-- 企业名称 -->
        <uni-forms-item :label="currentCompanyType.text+'名称'" name="companyName" required>
          <uni-easyinput v-model="ruleForm.companyName" type="text"
                         :placeholder="'请输入' + currentCompanyType.text + '名称'"/>
        </uni-forms-item>
        <!-- 统一社会信用代码 -->
        <uni-forms-item label="统一社会信用代码" name="regNum" required>
          <uni-easyinput v-model="ruleForm.regNum" type="text" placeholder="请输入18位的统一社会信用代码" maxlength="18"/>
        </uni-forms-item>
        <!-- 姓名 -->
        <uni-forms-item :label="currentCompanyType.leaderName+'姓名'" name="legalPerson" required>
          <uni-easyinput v-model="ruleForm.legalPerson" type="text"
                         :placeholder="'请输入' + currentCompanyType.leaderName+'姓名'"/>
        </uni-forms-item>
        <!-- 证件号码（我是企业法定代表人认证 不可修改） -->
        <uni-forms-item :label="currentCompanyType.leaderName+'证件号码'" name="legalPersonIdNumber" required>
          <uni-easyinput v-model="staffInfo.idNumber" maxlength="18" type="text" disabled/>
        </uni-forms-item>
        <!-- 手机号 -->
        <uni-forms-item :label="currentCompanyType.leaderName+'手机号'" name="legalPersonMobile" required>
          <uni-easyinput v-model="staffInfo.mobile" type="text" disabled/>
        </uni-forms-item>
        <!-- 手机号 -->
        <uni-forms-item label="管理员认证身份" name="managerTypeText" :required="true">
          <uni-easyinput v-model="managerTypeText" type="text" disabled class="disform"/>
        </uni-forms-item>
        <!-- 认证方式 -->
        <uni-forms-item label="单位实名认证方式" :required="true">
          <uni-data-select v-model="ruleForm.type" :localdata="typeArr" :clear="false"></uni-data-select>
        </uni-forms-item>
        <!-- 法定代表人身份认证显示 企业法定代表人 -->
        <view class="careful_p" v-show="ruleForm.type == 1 && managerType == 1">
          <p>法定代表人身份认证 <a>（即时认证，推荐使用）</a></p>
          <span>1、法定代表人必须持有中国大陆身份证，必须由本人进行认证操作。</span>
          <span>2、有限合伙企业请选择企业对公账户打款方式完成认证。</span>
          <span>3、外籍法定代表人请选择企业对公账户打款方式完成认证。</span>
        </view>
        <view v-show="ruleForm.type == 1 && managerType == 1">
          <checkbox-group @change="selectFa" style="margin:0rpx 0 25rpx;">
            <label>
              <checkbox value="face" color="#00a660" style="transform:scale(0.6)"/>
              <span style="font-size: 26rpx;">我同意励氪签采集人脸照片用于实名认证</span>
            </label>
          </checkbox-group>
        </view>
        <!-- 对公账户打款认证   企业授权代理人  企业法定代表人 -->
        <view class="careful_p" v-show="ruleForm.type == 2">
          <p>对公账户打款认证 <a>（工作日预计1小时左右至1个工作日审核完毕）</a></p>
          <span>需使用对公账户完成打款金额验证，即可通过认证。</span>
        </view>
        <uni-forms-item label="验证码" name="code" :required="true" v-if="ruleForm.type == 2">
          <view class="code">
            <uni-easyinput
                v-model="ruleForm.code"
                type="text"
                placeholder="请输入短信验证码"
                :maxlength="6"
                :clearable="false"/>
            <span class="codeBtn" @click="getMobileCode(4)">{{ counter }}</span>
          </view>
          <view class="sounds-text" v-show="voiceShow" @click="getMobileCode(104)">收不到短信？获取语音验证码</view>
        </uni-forms-item>
      </uni-forms>
      <view class="footer-Btn">
        <button @click="toBack" class="back-Btn">上一步</button>
        <button @click="submitForm" class="next-Btn">下一步</button>
      </view>
    </view>
  </view>
</template>

<script>

import config from '@/config'
import {getToken} from '@/utils/auth'
import {getCompany} from "@/api/ec/work/company/company";
import {listCompanyType} from "@/api/ec/work/company/companyType";
import {insertCertPageRecord} from "@/api/ec/work/company/companyCertification";
import {toGetSmsCode} from "@/api/ec/person/user/userInfo";

export default {
  data() {
    return {
      // 人脸认证选择
      confirmFace: '',
      // url地址
      host: config.baseUrl,
      // 认证步骤
      steps: [{title: '完善单位信息'}, {title: '核验单位信息'}, {title: '实名认证通过'}],
      // 认证方式
      typeArr: [{'value': 1, 'text': '法定代表人身份认证'}, {'value': 2, 'text': '对公账户打款认证'}],
      // 登录用户信息
      staffInfo: this.$store.getters.staffInfo,
      // 企业id
      companyId: '',
      // 1企业法定代表人 2企业授权代理人 3企业普通员工
      managerType: 1,
      // 组织类型
      companyTypeArr: [],
      // 当前操作的企业类型
      currentCompanyType: {},
      // 营业执照示例图
      businessImg: require('static/images/license.png'),
      // 管理员认证身份
      managerTypeText: '我是单位法定代表人',
      //短信验证码倒计时
      counter: "获取验证码",
      voiceShow: false, //语音验证码是否显示
      // 表单
      ruleForm: {
        legalPerson: "",
        companyName: '',
        regNum: "",
        companyType: 1,
        type: 1, //认证方式
        legalPersonMobile: "",
        file: '',
        managerType: 0,
      },
      // 表单验证
      rules: {
        legalPerson: {
          rules: [
            {required: true, errorMessage: "请输入姓名", trigger: "blur"},
          ]
        },
        file: {
          rules: [
            {required: true, errorMessage: "请上传多合一营业执照", trigger: "change"}
          ]
        },
        companyName: {
          rules: [
            {required: true, errorMessage: "请输入名称", trigger: "blur"},
          ]
        },
        regNum: {
          rules: [
            {required: true, errorMessage: "请输入统一社会信用代码", trigger: "blur"},
            {minLength: 18, maxLength: 18, errorMessage: "长度必须是18位", trigger: "blur"},
            {minLength: 18, maxLength: 18, errorMessage: "长度必须是18位", trigger: "change"},
          ]
        },
        companyType: {
          rules: [
            {required: true, errorMessage: "请选择组织类型", trigger: "change"},
          ]
        },
        type: {
          rules: [
            {required: true, errorMessage: "请选择认证方式", trigger: "change"},
          ]
        },
        legalPersonMobile: {
          rules: [
            {required: true, errorMessage: "请输入实名手机号", trigger: "blur"},
            {minLength: 11, maxLength: 11, trigger: "change", errorMessage: "手机号长度必须是11位",},
            {minLength: 11, maxLength: 11, trigger: "blur", errorMessage: "手机号长度必须是11位",},
          ],
        },
        code: {
          rules: [
            {required: true, errorMessage: "请填写验证码"},
          ]
        },
      },
    };
  },
  onLoad(option) {
    this.companyId = option.id;
    this.managerType = option.managerType;
    this.ruleForm.managerType = option.managerType;
    this.bindingRefreshData();
  },
  onUnload() {
    this.unbindingRefreshData();
  },
  created() {
    this.initCompanyType();
    this.initCompany();
  },
  methods: {
    /** 人脸照片用于实名认证选择 */
    selectFa(e) {
      this.confirmFace = e.detail.value[0]
    },
    /** 绑定 */
    bindingRefreshData() {
      // 证件图片剪切成功
      uni.$on('authenticationForLegalCropperSuccess', (base64, type) => {
        this.cropperSuccess(base64, type);
      });
    },
    /** 解除绑定 */
    unbindingRefreshData() {
      uni.$off('authenticationForLegalCropperSuccess');
    },
    /** 返回 */
    toBack() {
      uni.redirectTo({url: '/pages/authentication/companyRealname/start?id=' + this.companyId});
    },
    /** 预览图片*/
    previewImg(path) {
      uni.previewImage({urls: [path], current: 0});
    },
    /** 初始化获取企业信息 */
    initCompany() {
      uni.showLoading({title: '加载中...', mask: true});
      getCompany(this.companyId).then((response) => {
        uni.hideLoading()
        this.ruleForm.companyName = response.data.name;
        this.ruleForm.companyId = response.data.id;
        this.ruleForm.legalPersonMobile = this.staffInfo.mobile;
      }).catch(() => {
        uni.hideLoading()
      });
    },
    /** 获取企业类型 */
    initCompanyType() {
      uni.showLoading({title: '加载中...', mask: true});
      listCompanyType().then((response) => {
        uni.hideLoading()
        this.companyTypeArr = [];
        response.data.forEach(item => {
          this.companyTypeArr.push({value: item.id, text: item.name, leaderName: item.leaderName})
        })
        // 默认选中第一个
        this.ruleForm.companyTypeId = this.companyTypeArr[0].value;
        this.currentCompanyType = this.companyTypeArr[0];
      }).catch(() => {
        uni.hideLoading()
      });
    },
    /** 设置选中的企业类型 */
    selectCompanyTypeId(data) {
      //这里的selectList就是上面遍历的数据源
      let obj = this.companyTypeArr.find((item) => {
        //筛选出匹配数据
        return item.value === data;
      });
      this.currentCompanyType = obj;
    },
    /** 证书选取 */
    handleFileChange() {
      uni.navigateTo({url: "/pages/common/imageCropper/index?callbackMethod=authenticationForLegalCropperSuccess&width=1753&height=1240&type=" + this.managerType + "&imageSrc=" + encodeURIComponent(this.businessImg)});
    },
    /** 证件剪切成功回调方法 */
    cropperSuccess(base64, type) {
      // Base64字符串转二进制流
      let arrayBuffer = uni.base64ToArrayBuffer(base64.replace(/^data:image\/\w+;base64,/, ""))
      // 二进制流转blob
      let blob = new Blob([arrayBuffer], {type: "image/png"});
      setTimeout(() => {
        uni.showLoading({title: '加载中...', mask: true});
        uni.uploadFile({
          url: this.host + "/ec/certification/businessLicenseIdentify",
          file: blob,
          header: {'Authorization': 'Bearer ' + getToken(),},
          name: 'file',
          formData: {'companyId': this.companyId},
          success: (res) => {
            uni.hideLoading();
            let response = JSON.parse(res.data);
            if (response.code == 200) {
              let data = response.data;
              if (!!data) {
                this.ruleForm.companyName = data.companyName;
                this.ruleForm.regNum = data.regNum;
                this.ruleForm.legalPerson = data.legalPerson;
                this.ruleForm.capital = data.capital;
                this.ruleForm.validDate = data.validDate;
                this.ruleForm.address = data.address;
                this.ruleForm.regType = data.regType;
                this.businessImg = base64;
                this.ruleForm.file = true;
              } else {
                this.$modal.msgError(response.msg);
              }
              // 开发只要传任意图即可
              if(process.env.NODE_ENV === 'development'){
                this.businessImg = base64;
                this.ruleForm.file = true;
              }
            } else {
              this.$modal.msgError("检测失败！");
            }
          },
          complete: () => {
            uni.hideLoading();
          }
        });
      }, 100);
    },
    /** 获取手机验证码 **/
    getMobileCode(smsType) {
      let mobile = this.ruleForm.legalPersonMobile;
      const param = {mobile, smsType};
      toGetSmsCode(param).then(response => {
        this.$modal.msgSuccess("短信验证码已发送到您手机，请注意查收");
        this.counter = this.$smsCounter;
        const timer = setInterval(() => {
          this.counter--;
          if (this.counter <= 0) {
            this.counter = "获取验证码";
            this.voiceShow = true;
            clearInterval(timer);
          }
        }, 1000);
      })
    },
    /**下一步 需要判断身份 传值不一样*/
    submitForm() {
      this.$refs.ruleForm.validate().then((valid) => {
        if (valid) {
          if (this.ruleForm.type == 1) {
            // 法人身份认证
            this.submitLegalCertForm();
          } else {
            // 法人去打款
            this.submitLegalPaymentForm();
          }
        }
      });
    },
    /**下一步 法人身份认证*/
    submitLegalCertForm() {
      if (this.confirmFace != 'face') {
        this.$modal.msgError("请勾选协议")
        return;
      }
      this.ruleForm.certifyType = this.ruleForm.type;
      this.ruleForm.path = "/companyRealname/resultQr";
      let certInfo = JSON.stringify(this.ruleForm);
      let formData = {"certInfo": certInfo};
      insertCertPageRecord(formData).then(response => {
        // 新增企业认证
        let arrayBuffer = uni.base64ToArrayBuffer(this.businessImg.replace(/^data:image\/\w+;base64,/, ""))
        let blob = new Blob([arrayBuffer], {type: "image/png"});
        uni.showLoading({title: '加载中...', mask: true});
        uni.uploadFile({
          url: this.host + "/ec/certification",
          file: blob,
          header: {'Authorization': 'Bearer ' + getToken(),},
          name: 'imgPath',
          formData: {'certInfo': certInfo},
          success: (res) => {
            uni.hideLoading();
            let response = JSON.parse(res.data);
            if (response.code == 200) {
              let data = response.data;
              uni.navigateTo({url: '/pages/authentication/companyRealname/resultQr?id=' + this.companyId + '&managerType=' + this.managerType + '&companyName=' + this.ruleForm.companyName});
            } else {
              this.$modal.msgError("操作失败！");
            }
          },
          complete: () => {
            uni.hideLoading();
          }
        });
      }).catch(() => {
        this.$modal.closeLoading()
      });
    },
    /**下一步 法人去打款*/
    submitLegalPaymentForm() {
      // Base64字符串转二进制流
      let arrayBuffer = uni.base64ToArrayBuffer(this.businessImg.replace(/^data:image\/\w+;base64,/, ""))
      let blob = new Blob([arrayBuffer], {type: "image/png"});
      this.ruleForm.path = "/companyRealname/examine";
      this.ruleForm.certifyType = 0;// 打款类型
      let certInfo = JSON.stringify(this.ruleForm);
      uni.showLoading({title: '加载中...', mask: true});
      uni.uploadFile({
        url: this.host + "/ec/certification/insertCertPageRecord",
        file: blob,
        header: {'Authorization': 'Bearer ' + getToken(),},
        name: 'imgPath',
        formData: {'certInfo': certInfo},
        success: (res) => {
          uni.hideLoading();
          let response = JSON.parse(res.data);
          if (response.code == 200) {
            uni.redirectTo({url: '/pages/authentication/companyRealname/examine?id=' + this.companyId + '&managerType=' + this.managerType});
          } else {
            this.$modal.msgError("操作失败！");
          }
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .uni-forms-item__label {
  height: 50rpx;
}

::v-deep .uni-forms-item {
  margin-bottom: 28rpx;
}

.disform ::v-deep .uni-input-input {
  color: #666666;
}

page {
  background: $uni-bg-color;
}

.img_span {
  font-size: 22rpx;
  color: #999999;
  margin-left: 20rpx;
}

.ag_container {
  position: relative;
  overflow: hidden;
  padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
}

.agree_jn {
  margin-top: 40rpx;
  padding: 0 30rpx;
  position: relative;

  .upfile {
    display: flex;
    align-items: center;

    .upfile-p {
      margin: 0;
    }
  }

  .careful_p {
    color: #a4a2a8;
    font-size: 24rpx;
    padding: 12rpx 16rpx;
    background-color: #e6f6ef;
    border: solid 1rpx #99dbbf;
    line-height: 40rpx;
    margin-bottom: 28rpx;

    p:first-child {
      font-size: 24rpx;
      color: #5c5a5a;
      margin: 0;

      a {
        color: red;
        font-size: 20rpx;
      }
    }

    span {
      display: block;
    }
  }

  // 获取验证码
  .code {
    display: flex;
    justify-content: space-around;
    align-items: center;
    position: relative;

    .codeBtn {
      color: $uni-color-primary;
      position: absolute;
      right: 20rpx;
    }

  }

  .sounds-text {
    text-align: right;
    margin-top: 6rpx;
    color: #777;
    font-size: 26rpx;
  }

  .care_p {
    color: #a4a2a8;
    text-align: left;
    text-indent: 2em;
    font-size: 24rpx;
    background-color: #e6f6ef;
    border: solid 1rpx #99dbbf;
    padding: 12rpx;
    margin: 30rpx 0 10rpx 0;
  }

  // 认证btn
  .footer-Btn {
    margin: 50rpx 0 60rpx 0;
    display: flex;
    justify-content: space-between;

    button {
      width: 44%;
      font-size: 28rpx;
    }

    .next-Btn {
      background-color: $uni-color-primary;
      border-radius: 10rpx;
      color: #fff;
      margin-left: 70rpx;
    }

    .back-Btn {
      border-radius: 10rpx;
      border: solid 1rpx $uni-color-primary;
      color: $uni-color-primary;
      background: #fff;
    }
  }
}
</style>
